import Grid from "./grid/grid";
import {Scope} from "../scope";
import {ImportExcelOption, ImportResult, XLSX} from "../xlsx";
import ExcelImport from "./form/excelimport";
import _ from "lodash";
import {formatter} from "../extend";
import {RefreshMode, YvanEventDispatch} from "..";
import Spliter from "./spliter";

interface Ref {
    dataGrid: Grid
    errMsgGrid: Grid
    excelImport: ExcelImport
    spliter: Spliter
}

interface Input {
    option: ImportExcelOption
}

interface MainData {
    dataKey: "allData"|"okData"|"errorData"
}

const dataMap = {
    'allData': '所有数据',
    'okData': '正确数据',
    'errorData': '错误数据'
}

export default class ExcelImportDialog extends Scope<Input, Ref> {

    main: MainData = this.$$({
        dataKey: 'okData',
    })



    constructor(inParamter: Input) {
        super(inParamter);

        /** 控制默认显示的数据 **/
        if (inParamter.option.defaultShowData === 'allData'
            || inParamter.option.defaultShowData === 'okData'
            || inParamter.option.defaultShowData === 'errorData') {
            this.main.dataKey = inParamter.option.defaultShowData;
        }

        /** 构造导入数据的表格 **/
        let grid: any = []
        const item = {
            field: "__importID__",
            title: "行号",
            width: 80,
            onStyle: "markRowErrorToCell",
            onCellClicked: this.onCellClicked
        }
        const columns = _.cloneDeep(inParamter.option.fields);
        for (let i = 0; i < inParamter.option.fields.length; i++) {
            const a = columns[i];
            _.set(a, 'onStyle', 'markCellError');
            _.set(a, 'onCellClicked', 'onCellClicked');
        }
        columns.splice(0, 0, item);

        /** 构造错误信息的表格 **/
        const emColumns: any [] = [
            {field: "errorId", title: "ID", hidden: true},
            {field: "importID", title: "行号", width: 80},
            {field: "errormessage", title: "错误信息", width: 200},
            {field: "value", title: "值", width: 120},
            {field: "title", title: "字段名", width: 120},
            {field: "field", title: "字段", width: 120}
        ];
        const paginationOption = {
            size: "small",
            defaultPageSize: 10,
            pageSizeOptions: ['10', '20', '50', '100', '200', '500', '1000'],
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total: number) => `总共 ${total} 条`
        };

        /** 分页处理 **/
        const dataGridPageOption = _.cloneDeep(paginationOption)
        const errorMsgGridPageOption = _.cloneDeep(paginationOption)
        let dataGridPageAble = true;
        let errorMsgGridPageAble = true;
        if (typeof inParamter.option.dataGridPageSize === 'number') {
            _.set(dataGridPageOption, 'defaultPageSize', inParamter.option.dataGridPageSize)
            if (inParamter.option.dataGridPageSize === 0) {
                dataGridPageAble = false
            }
        }

        if (typeof inParamter.option.errorMsgGridPageSize === 'number') {
            _.set(errorMsgGridPageOption, 'defaultPageSize', inParamter.option.errorMsgGridPageSize)
            if (inParamter.option.errorMsgGridPageSize === 0) {
                errorMsgGridPageAble = false
            }
        }

        if (this.inParamter.option.errMsgGridColWidths) {
            let len = this.inParamter.option.errMsgGridColWidths.length
            len = len < emColumns.length ? len : emColumns.length
            for (let i = 1; i < len; i++) {
                const el = emColumns[i];
                el.width = this.inParamter.option.errMsgGridColWidths[i]
            }
        }

        const dataOption:any = [];
        if (!inParamter.option.hidAllDataGrid) {
            dataOption.push({label: '所有数据', value: 'allData'})
        }
        if (!inParamter.option.hidOKDataGrid) {
            dataOption.push({label: '正确数据', value: 'okData'})
        }
        if (!inParamter.option.hidErrorDataGrid) {
            dataOption.push({label: '错误数据', value: 'errorData'})
        }

        /** 生成数据的表格 **/
        grid = {
            view: 'grid',
            className:'excell-import-grid-title',
            ref: 'dataGrid',
            idField: "__importID__",
            exportExcelName: {$watch: () => {
                    return dataMap[this.main.dataKey] + '.xlsx';
                }},
            toolbar: [
                {
                    view:'form',
                    items:[
                        {
                            view: 'radio',
                            bind: 'main.dataKey',
                            optionType: 'button',
                            buttonStyle: 'solid',
                            data: dataOption
                        }
                    ]
                }
            ],
            columns: columns,
            autoDataSource: true,
            pagination: dataGridPageAble,
            paginationOption: dataGridPageOption,
            dataSource: {
                func: (params: { data: { dataKey: "allData" | "okData" | "errorData" } }) => {
                    return this.importResult[params.data.dataKey];
                },
                params: {
                    dataKey: {$watch: () => this.main.dataKey}
                }
            },
            onDataSourceAfter: (sender: Grid, dataOrgin: any[], raw: any, api: any, isExportData: boolean) => {
                if (isExportData === true) {
                    return dataOrgin
                }
                const offset = (sender.currentPage - 1) * sender.pageSize
                const endOffset = (offset + sender.pageSize > dataOrgin.length) ? dataOrgin.length : offset + sender.pageSize
                return {
                    pagination: {
                        current: sender.currentPage,
                        total: dataOrgin.length,
                        size: sender.pageSize
                    },
                    data: dataOrgin.slice(offset, endOffset)
                }
            }
        }

        const topItems = [
            {
                view: "row",
                className:'excel-import-row',
                items: [
                    // {
                    //     view: "col",
                    //     span: 2,
                    //     items: [
                            
                    //     ]
                    // },
                    {
                        view: "col",
                        className:'excel-import-col',
                        span: 5,
                        items: [
                            {
                                view: 'excelImport',
                                className:'excel-import',
                                ref: 'excelImport',
                                fields: this.inParamter.option.fields,
                                rowValidate: this.inParamter.option.rowValidate,
                                dataStartRow: this.inParamter.option.dataStartRow || 2,
                                titleRowNumber: this.inParamter.option.titleRowNumber || 1,
                                onChange: this.onChange,
                                afterClientValidate: this.inParamter.option.afterClientValidate,
                                fieldValidate: this.inParamter.option.fieldValidate
                            }
                        ]
                    },
                    {
                        view: "col",
                        span: 10,
                        items: [
                            {
                                view: 'button',
                                text: "重新导入",
                                type: "primary",
                                icon:"fa fa-repeat",
                                onClick: this.reImportExcel
                            },
                            {
                                view: 'button',
                                type: "primary",
                                text: "下载模版",
                                icon:"fa fa-download",
                                onClick: this.onDownloadClick
                            }
                        ]
                    }
                ]
            },
        ]

        const topCrads = [{
            view: 'card',
            size: 'small',
            className: 'form-item-no-bottom',
            items: topItems
        }]

        if (_.isArray(this.inParamter.option.toolBar)) {
            topCrads.push({
                view: 'card',
                size: 'small',
                className: 'form-item-no-bottom',
                items: this.inParamter.option.toolBar
            });
        }

        this.vjson = {
            view: 'page',
            height: '90%',
            width: '90%',
            title: this.inParamter.option.title,
            items: [
                ...topCrads,
                this.inParamter.option.hidErrorMsgGrid === true ?
                    {
                        view: 'card',
                        size: 'small',
                        items: [
                            grid
                        ]
                    } :
                    {
                        view: 'spliter',
                        split: 'vertical',
                        ref: 'spliter',
                        defaultSize: '10%s',
                        primary: 'second',
                        minSize: '100px',
                        maxSize: '1200px',
                        items: [
                            {
                                view: 'card',
                                size: 'small',
                                items: [
                                    grid
                                ]
                            },
                            {
                                view: 'card',
                                size: 'small',
                                items: [{
                                    view: 'grid',
                                    title: '错误明细',
                                    ref: 'errMsgGrid',
                                    idField: "errorId",
                                    exportExcelName: "错误明细.xlsx",
                                    columns: emColumns,
                                    autoDataSource: true,
                                    pagination: errorMsgGridPageAble,
                                    paginationOption: errorMsgGridPageOption,
                                    dataSource: {
                                        func: () => {
                                            return this.importResult.errorMsgData
                                        }
                                    },
                                    onDataSourceAfter: (sender: Grid, dataOrgin: any[], raw: any, api: any, param: RefreshMode) => {
                                        if (param.isExportData === true || sender.props.vjson.pagination == false) {
                                            return dataOrgin
                                        }
                                        const offset = (sender.currentPage - 1) * sender.pageSize
                                        const endOffset = (offset + sender.pageSize > dataOrgin.length) ? dataOrgin.length : offset + sender.pageSize
                                        return {
                                            pagination: {
                                                current: sender.currentPage,
                                                total: dataOrgin.length,
                                                size: sender.pageSize
                                            },
                                            data: dataOrgin.slice(offset, endOffset)
                                        }
                                    },
                                    onRowSelect: (sender: Grid, data: any) => {
                                        this.refs.dataGrid?.selectRow(data.importID)
                                    }
                                }]
                            }
                        ]
                    },
            ]
        }
        if (this.inParamter.option.onClose) {
            this.vjson.afterClose = ()=>{
                YvanEventDispatch(this.inParamter.option.onClose, this.refs.excelImport);
                this.close();
            }
        }


    }

    importResult: ImportResult = {
        allData: [],
        okData: [],
        errorData: [],
        errorMsgData: [],
    }

    markCellError(sender: ExcelImport, params: any) {
        for (let i = 0; i < this.importResult.errorMsgData.length; i++) {
            const v = this.importResult.errorMsgData[i];
            if (v.importID === params.data.__importID__ && params.field === v.field) {
                return {backgroundColor: '#ff4d4f'};
            }
        }
    }

    markRowErrorToCell(sender: ExcelImport, params: any) {
        for (let i = 0; i < this.importResult.errorMsgData.length; i++) {
            const v = this.importResult.errorMsgData[i];
            if (v.importID === params.data.__importID__) {
                return {backgroundColor: '#ff4d4f'};
            }
        }
    }

    onCellClicked(sender: ExcelImport, params: any) {
        let marked: boolean | undefined = false;
        if (params.field === "__importID__") {
            marked = this.refs.errMsgGrid?.selectRow(params.data.__importID__ + "")
            if (!marked) {
                for (let i = 0; i < this.importResult.errorMsgData.length; i++) {
                    const el = this.importResult.errorMsgData[i];
                    if (el.errorId.startsWith(params.data.__importID__ + "_")) {
                        marked = this.refs.errMsgGrid?.selectRow(el.errorId)
                        break
                    }
                }
            }

        } else {
            marked = this.refs.errMsgGrid?.selectRow(params.data.__importID__ + "_" + params.field)
        }

        if (!marked) {
            this.refs.errMsgGrid?.gridApi.deselectAll();
        }

    }

    onDownloadClick() {
        if (this.inParamter.option.dowLoadUrl && this.inParamter.option.dowLoadUrl.length > 0) {
            window.location.href = this.inParamter.option.dowLoadUrl;
            return
        }
        let xt: string[] = []
        _.forEach(this.inParamter.option.fields, (v) => {
            xt.push(v.title);
        })
        const filename = this.inParamter.option.templateName ? this.inParamter.option.templateName : "模版.xlsx"; //文件名称
        var ws_name = "Sheet1"; //Excel第一个sheet的名称
        var wb = XLSX.utils.book_new(), ws = XLSX.utils.aoa_to_sheet([xt]);
        XLSX.utils.book_append_sheet(wb, ws, ws_name);  //将数据添加到工作薄
        XLSX.writeFile(wb, filename); //导出Excel
    }

    onChange(sender: any, result: ImportResult) {
        this.importResult = result
        this.refs.dataGrid?.refresh();
        this.refs.errMsgGrid?.refresh();
        YvanEventDispatch(this.inParamter.option.onImportAfter, this, result);

    }

    reImportExcel() {
        this.refs.excelImport?.reOpen();
    }

    // @ts-ignore
    vjson: any = {}


}